package com.group.neps.controller;


import com.group.common.users.NEPSUser;
import com.group.common.utils.MyUtils;
import com.group.neps.entity.*;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.Stage;
import javafx.util.StringConverter;

import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;

public class FeedbackProvideViewController {
    @FXML
    private ComboBox<Province> cmbProvince;
    @FXML
    private ComboBox<City> cmbCity;
    @FXML
    private TextField txtAddress;
    @FXML
    private ComboBox<String> cmbLevel;
    @FXML
    private TextArea txtFeedback;
    @FXML
    private Button btnHistory;
    @FXML
    private DatePicker datePicker;


    private static NEPSUser user;
    private HashMap<String, Province> provinceMap = new HashMap<>();
    private HashMap<String, City> cityMap = new HashMap<>();
    private ArrayList<RowAqiData> rowAqiDataArrayList = new ArrayList<>();

    public static NEPSUser getUser() {
        return user;
    }

    public static void setUser(NEPSUser user) {
        FeedbackProvideViewController.user = user;
    }

    @FXML
    public void initialize() throws IOException {
        // 设置ComboBox显示方式
        setupComboBoxDisplay();
        // 设置省份选择监听器
        setupProvinceSelectionListener();
        // 初始化污染等级下拉框
        initLevelComboBox();

        //设置默认值为当前系统时间
        datePicker.setValue(LocalDate.now());
        //添加监听时间，处理选择的时间
        datePicker.valueProperty().addListener(new ChangeListener<LocalDate>() {
            @Override
            public void changed(ObservableValue<? extends LocalDate> observableValue, LocalDate oldDate, LocalDate newDate) {
                System.out.println("选择的日期为：" + newDate);
            }
        });
    }

    private void setupComboBoxDisplay() {
        // 设置省份ComboBox显示
        cmbProvince.setConverter(new StringConverter<Province>() {
            @Override
            public String toString(Province province) {
                return province == null ? "" : province.getName();
            }

            @Override
            public Province fromString(String string) {
                return null; // 不需要实现
            }
        });

        // 设置城市ComboBox显示
        cmbCity.setConverter(new StringConverter<City>() {
            @Override
            public String toString(City city) {
                return city == null ? "" : city.getName();
            }

            @Override
            public City fromString(String string) {
                return null; // 不需要实现
            }
        });

        // 填充省份数据
        provinceMap = MyUtils.readFileToHashMap("group/data/location_hashmap.dat");
        ObservableList<Province> provinces = FXCollections.observableArrayList(provinceMap.values());
        cmbProvince.setItems(provinces);
    }

    private void setupProvinceSelectionListener() {
        //监听选中的省份
        cmbProvince.getSelectionModel().selectedItemProperty().addListener((obs, oldProvince, newProvince) -> {
            cmbCity.getItems().clear();
            if (newProvince != null) {
                // 获取选中省份的城市列表
                ObservableList<City> cities = FXCollections.observableArrayList(
                        newProvince.getCities().values()
                );
                cmbCity.setItems(cities);
            }
        });
    }

    private void initLevelComboBox() {
        // 确保 cobLevel 已经通过 @FXML 注入，并为等级下拉列表赋初值
        if (cmbLevel != null) {
            ObservableList<String> levels = FXCollections.observableArrayList(
                    "ROW_AQI_LEVEL_1", "ROW_AQI_LEVEL_2", "ROW_AQI_LEVEL_3", "ROW_AQI_LEVEL_4", "ROW_AQI_LEVEL_5", "ROW_AQI_LEVEL_6");
            cmbLevel.setItems(levels);
        } else {
            System.err.println("Error: cobLevel ComboBox is not initialized");
        }
    }

    public void commit() throws IOException, ClassNotFoundException {
        // 获取监督员提交的信息
        Province province = cmbProvince.getValue();
        cityMap = province.getCities();
        City city = cmbCity.getValue();
        String level = cmbLevel.getValue();
        LocalDate time = datePicker.getValue();
        RowAqiLevel rowAqiLevel = RowAqiLevel.valueOf(level);
        Location location = new Location(provinceMap.get(province.getCode()), cityMap.get(city.getCode()), txtAddress.getText());
        String remark = txtFeedback.getText();

        // 创建RowAqiData对象并写入文件保存
        RowAqiData rowAqiData = new RowAqiData(user, time, location, rowAqiLevel, remark);
        rowAqiDataArrayList.add(rowAqiData);
        MyUtils.writeFile("group/data/row_aqi_data_arraylist.dat", rowAqiDataArrayList);
        MyUtils.showAlert("反馈提交",null, "反馈提交成功", Alert.AlertType.INFORMATION);
    }

    public void history() {
        //跳转到历史记录界面
        MyUtils.showView((Stage) btnHistory.getScene().getWindow(), "group/neps/view/FeedbackDataView.fxml");
    }
}
